package com.example.usb.thread;

import android.os.Handler;

import com.example.usb.MyApplication;
import com.example.usb.dao.DbConstant;
import com.example.usb.dao.entity.PhotoPicBean;
import com.example.usb.dao.util.CalendarUtil;
import com.example.usb.dao.util.PhotoPicDaoUtil;
import com.lib.uvccamera.utils.AppUtil;
import com.lib.uvccamera.utils.DebugLog;
import com.example.usb.util.PermissionUtil;
import com.example.usb.util.SpUtils;
import com.lib.uvccamera.UVCCameraHelper;
import com.lib.uvccamera.utils.FileUtils;
import com.serenegiant.usb.common.AbstractUVCCameraHandler;

import java.io.File;
import java.io.FileNotFoundException;

import static com.example.usb.dao.util.CalendarUtil.DATE_FORMAT_YMDHMS;
import static com.lib.uvccamera.utils.DebugLog.LOGHsc;

/**
 * Created Date 2019/2/24.
 *
 * @author liangkun
 * ClassDescription： 自动拍照线程
 */
public class AutoTakePhotoThread  implements Runnable{
    private UVCCameraHelper mCameraHelper ;
    private Handler handler ;
    public AutoTakePhotoThread(UVCCameraHelper mCameraHelper, Handler handler) {
        this.mCameraHelper =mCameraHelper;
        this.handler =handler;
    }

    @Override
    public void run() {
        if (!SpUtils.getBoolean(PermissionUtil.permission)) {
            DebugLog.d(LOGHsc+" 没有读写权限-----------" );
            return ;
        }

        if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
            DebugLog.d(LOGHsc+" 没有USB连接-----------"+mCameraHelper+" --- "+mCameraHelper.isCameraOpened());
            return ;
        }
        long takeTime = System.currentTimeMillis();
        String picPath = UVCCameraHelper.ROOT_PATH +AppUtil.getPackageName(MyApplication.getContext())+File.separator + takeTime
                + UVCCameraHelper.SUFFIX_JPEG;
        DebugLog.d(LOGHsc + " picPath ---- " + picPath);
        mCameraHelper.capturePicture(picPath, new AbstractUVCCameraHandler.OnCaptureListener() {
            @Override
            public void onCaptureResult(String path) {
                DebugLog.d(LOGHsc+" save path：" + path);
                try {
                    String md5str = FileUtils.getStringMd5(new File(picPath));
                    PhotoPicBean photoPicBean = new PhotoPicBean();
                    photoPicBean.setMd5(md5str);
                    photoPicBean.setDataTime(CalendarUtil.formatTime(DATE_FORMAT_YMDHMS,takeTime));
                    photoPicBean.setFilePath(path);
                    photoPicBean.setDetection(DbConstant.PIC_NO_DETECTION);
                    photoPicBean.setFileName(String.valueOf(takeTime));
                    PhotoPicDaoUtil.getInstance().insertPicBean(photoPicBean);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        });
        handler.postDelayed(this,DbConstant.AUTO_TAKE_PIC);
    }
}
